/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司   All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.beanvalidator.BeanValidators;
import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.DateUtils;
import cn.net.ecode.common.utils.excel.ExportExcel;
import cn.net.ecode.common.utils.excel.ImportExcel;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Employee;
import cn.net.ecode.modules.sys.entity.Post;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.service.EmployeeService;
import cn.net.ecode.modules.sys.service.PostService;
import cn.net.ecode.modules.sys.service.RoleService;
import cn.net.ecode.modules.sys.utils.UserUtils;

import com.google.common.collect.Lists;

/**
 * 员工管理Controller
 * @author jiaoanjian、ThinkGem
 * @version 2015-4-24
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/employee")
public class EmployeeController extends BaseController {

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private PostService postService;

	@Autowired
	private RoleService roleService;

	/**
	 * 获取数据
	 * @param empCode 获取数据编号
	 * @param isNewRecord 如果新记录，则不进行查询
	 * @return
	 */
	@ModelAttribute
	public Employee get(String empCode, boolean isNewRecord) {
		Employee employee = employeeService.get(empCode, isNewRecord);
		if (employee.getIsLoginUser() == null) {
			employee.setIsLoginUser(Global.NO);
		}
		return employee;
	}

	@RequiresPermissions("sys:employee:view")
	@RequestMapping(value = {"list", ""})
	public String list(Employee employee, Model model) {
		Post post = new Post();
		post.setStatus(Post.STATUS_NORMAL);
		model.addAttribute("allPosts", postService.findList(post));
		return "modules/sys/employeeList";
	}

	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "listData")
	public Page<Employee> listData(Employee employee, HttpServletRequest request, HttpServletResponse response) {
		Page<Employee> page = null;
		employee.getOffice().setIsQueryChildren(true);
		employee.getCompany().setIsQueryChildren(true);
		if(employee.isAll()){
			page = employeeService.findAllPage(new Page<Employee>(request, response), employee);
		}else{
			page = employeeService.findPage(new Page<Employee>(request, response), employee);
		}
		return page;
	}

	@RequiresPermissions("sys:employee:view")
	@RequestMapping(value = "form")
	public String form(Employee employee, Model model) {

		// 设置默认的公司
		if (employee.getCompany() == null || employee.getCompany().getId() == null) {
			if (UserUtils.getUser().getEmployee() != null) {
				employee.setCompany(UserUtils.getUser().getEmployee().getCompany());
			}
		}
		
		// 设置默认的部门
		if (employee.getOffice() == null || employee.getOffice().getId() == null) {
			if (UserUtils.getUser().getEmployee() != null) {
				employee.setOffice(UserUtils.getUser().getEmployee().getOffice());
			}
		}
		
		// 获取当前编辑用户的岗位
		employee.setPostList(postService.getPostByEmployee(employee));
		model.addAttribute("employee", employee);
		
		// 获取岗位列表
		Post post = new Post();
		post.setStatus(Post.STATUS_NORMAL);
		model.addAttribute("allPosts", postService.findList(post));
		
		// 获取可分配的权限
		model.addAttribute("allRoles", roleService.findList(new Role()));
		
		return "modules/sys/employeeForm";
	}

	@RequiresPermissions("sys:employee:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Employee employee, Model model, RedirectAttributes redirectAttributes) {
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, employee)) {
			return renderResult(Global.FALSE, message);
		}
//		if (StringUtils.isBlank(employee.getEmpNo())){
//			employee.setEmpNo(employee.getEmpCode());
//		}
		employeeService.save(employee);
		return renderResult(Global.TRUE, "保存员工'" + employee.getEmpName() + "'成功！");
	}

	/**
	 * 删除员工
	 * @param employee
	 * @return
	 */
	@RequiresPermissions("sys:employee:delete")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Employee employee) {
		employeeService.deleteEmployee(employee);
		return renderResult(Global.TRUE, "删除员工'" + employee.getEmpName() + "'成功！");
	}

	/**
	 * 员工离职
	 * @param employee
	 * @return
	 */
	@RequiresPermissions("sys:employee:leave")
	@ResponseBody
	@RequestMapping(value = "leave")
	public String leave(Employee employee) {
		employeeService.leaveEmployee(employee);
		return renderResult(Global.TRUE, "操作员工'" + employee.getEmpName() + "'离职成功！");
	}

	/**
	 * 下载导入员工数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:employee:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "员工数据导入模板.xlsx";
			List<Employee> list = Lists.newArrayList();
			Employee employee = UserUtils.getUser().getEmployee();
			if (employee != null && StringUtils.isNotBlank(employee.getEmpCode())) {
				employee.setPostList(postService.getPostByEmployee(employee));
				employee.setLoginInfo(UserUtils.getUser());
				list.add(employee);
			}
			new ExportExcel("员工数据", Employee.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/employee/?repage";
	}

	/**
	 * 导出员工数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:employee:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(Employee employee, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "员工数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			List<Employee> list = employeeService.findExportList(employee);
			new ExportExcel("员工数据", Employee.class).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出员工失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/employee/?repage";
	}

	/**
	 * 导入员工数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:employee:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/employee/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Employee> list = ei.getDataList(Employee.class);
			for (Employee employee : list) {
				try {
					if ("true".equals(checkEmpNo("", employee.getEmpCode()))) {
						BeanValidators.validateWithException(validator, employee);
						//BeanValidators.validateWithException(validator, employee.getLoginInfo());
						if (StringUtils.isBlank(employee.getEmpNo())) {
							employee.setEmpNo(employee.getEmpCode());
						}
						employeeService.save(employee);
						successNum++;
					} else {
						failureMsg.append("<br/>员工编号 " + employee.getEmpCode() + " 已存在; ");
						failureNum++;
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>员工编号 " + employee.getEmpCode() + " 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("<br/>员工编号 " + employee.getEmpCode() + " 导入失败：" + ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条员工，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条员工" + failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入员工失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/employee/?repage";
	}

	/**
	 * 验证编码是否有效
	 * @param oldEmpCode
	 * @param empCode
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:employee:edit")
	@RequestMapping(value = "checkEmpCode")
	public String checkEmpCode(String oldEmpCode, String empCode) {
		if (empCode != null && empCode.equals(oldEmpCode)) {
			return "true";
		} else if (empCode != null && employeeService.get(empCode) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证工号是否有效
	 * @param oldEmpNo
	 * @param empNo
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:employee:edit")
	@RequestMapping(value = "checkEmpNo")
	public String checkEmpNo(String oldEmpNo, String empNo) {
		if (empNo != null && empNo.equals(oldEmpNo)) {
			return "true";
		} else if (empNo != null && employeeService.getByEmpNo(empNo) == null) {
			return "true";
		}
		return "false";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = { "employeeSelect" })
	public String employeeSelect(Employee employee, HttpServletRequest request, Model model) {
		model.addAttribute("selectData", request.getParameter("selectData")); // 指定默认选中
		return "modules/sys/employeeSelect";
	}

}